package controllers

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	"github.com/jinzhu/copier"
	"goravel/app/models"
	"goravel/app/services"
	"goravel/app/types"
)

type DictController struct {
	DbServer services.DBServer
}

func NewDictController() *DictController {
	return &DictController{
		DbServer: services.NewDictService(),
	}
}

// Index 字典列表
// @Summary      字典列表
// @Tags         Dict
// @Router       /dict [get]
func (c *DictController) Index(ctx http.Context) http.Response {
	var model []models.SysDict
	var listResp []types.SysDictListResp
	query := facades.Orm().Query().OrderBy("id", "desc")
	data, meta, err := c.DbServer.ListPage(ctx, &model, query, &listResp)
	if err != nil {
		return services.NewApiService(ctx).Error500(err.Error())
	}
	return services.NewApiService(ctx).DataPage(data, meta)
}

// Show 字典详情
// @Summary      字典详情
// @Tags         Dict
// @Router       /dict/{id} [get]
func (c *DictController) Show(ctx http.Context) http.Response {
	return services.NewApiService(ctx).OK("Show")
}

// Store 新增字典
// @Summary      新增字典
// @Tags         Dict
// @Router       /dict [post]
func (c *DictController) Store(ctx http.Context) http.Response {
	var createReq types.SysDictCreateReq
	var err error
	err = ctx.Request().Bind(&createReq)
	if err != nil {
		return services.NewApiService(ctx).Error500("参数错误")
	}
	var model models.SysDict
	err = copier.Copy(&model, &createReq)
	if err != nil {
		return services.NewApiService(ctx).Error500("参数错误")
	}
	err = facades.Orm().Query().Create(&model)
	if err != nil {
		return services.NewApiService(ctx).Error500("数据库插入错误")
	}
	return services.NewApiService(ctx).OK("stored")
}

// Update 更新字典
// @Summary      更新字典
// @Tags         Dict
// @Router       /dict/{id} [put]
func (c *DictController) Update(ctx http.Context) http.Response {
	return services.NewApiService(ctx).OK("Update")
}

// Destroy 删除字典
// @Summary      删除字典
// @Tags         Dict
// @Router       /dict/{id} [delete]
func (c *DictController) Destroy(ctx http.Context) http.Response {
	id := ctx.Request().RouteInt64("id")
	var model models.SysDict
	err := facades.Orm().Query().FindOrFail(&model, id)
	if err != nil {
		return services.NewApiService(ctx).Error500("无相关数据")
	}
	_, err = facades.Orm().Query().Delete(&model)
	if err != nil {
		return services.NewApiService(ctx).Error500("删除失败")
	}
	return services.NewApiService(ctx).OK("deleted")
}
